import { Request } from "express";
import Useragent from "useragent";
import { getIpAddrInfo } from "../../../api/common";
import iconv from "iconv-lite";
import { LoginLogService } from "../../../services/system/LoginLogService";

interface IClientInfo {
  loginId: string;
  ipAddr: string;
  browser: string;
  os: string;
  location: string;
  status: string;
  remark: string;
}

export class ClientInfo {
  public static async getClientInfo(req: Request, status, remark) {
    const agent = Useragent.parse(req.headers["user-agent"]);
    const os = agent.os.toJSON().family;
    const browser = agent.toAgent();

    const clientInfo: IClientInfo = {
      loginId: req.body.loginId,
      ipAddr: req.ip as string,
      browser: browser,
      os: os,
      location: "未知",
      status,
      remark,
    };

    try {
      const res = await getIpAddrInfo(req.ip as string);
      const str = JSON.parse(iconv.decode(res as any, "gbk"));
      clientInfo.location = str.addr;
      clientInfo.ipAddr = str.ip;
    } catch (error) {}

    await LoginLogService.add(clientInfo as any);
    return clientInfo;
  }
}
